﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace MyKnights.Entity
{
    [XmlRoot("UserData")]
    public class UserData
    {
        [XmlArray("Profiles"), XmlArrayItem("Profile")]
        public List<Profile> Profiles { get; set; } = new List<Profile>();

        [XmlElement("AppStatus")]
        public AppStatus AppStatus { get; set; } = new AppStatus();

        private bool _isFileSaving;
        public UserData()
        {

        }

        public void AddProfile(Profile storedProfile)
        {
            foreach (var profile in Profiles)
            {
                //已存在同名,取消增加
                if (storedProfile.Name.Equals(profile.Name)) return;
            }

            foreach (Profile profile in Profiles)
            {
                profile.Selected = false;
            }
            Profiles.Add(new Profile
            {
                Name = storedProfile.Name,
                Selected = true,
                KnightVisibility = storedProfile.KnightVisibility
            });
            SaveToFile();
        }

        public void DeleteProfile(Profile profile)
        {
            for (int i = 0; i < Profiles.Count; i++)
            {
                if (profile.Name.Equals(Profiles[i].Name))
                {
                    Profiles.Remove(Profiles[i]);
                    break;
                }
            }
            SaveToFile();
        }

        public Profile GetSelectedProfile()
        {
            Profile selProfile = null;
            foreach (var profile in Profiles)
            {
                if (profile.Selected) return profile;
                selProfile = profile;
            }
            if (selProfile == null)
            {
                selProfile = new Profile { Name = "默认", Selected = true };
                Profiles.Add(selProfile);
            }
            return selProfile;
        }

        public void SaveToFile()
        {
            if (_isFileSaving) return;
            _isFileSaving = true;
            TUtil.XmlHelper.SerializerToFile(this, Const.Path.UserDataXml);
            _isFileSaving = false;
        }

        public static UserData LoadFromFile()
        {
            return TUtil.XmlHelper.XmlDeserializeFromFile<UserData>(Const.Path.UserDataXml);
        }

        public static UserData Initialize()
        {
            if (File.Exists(Const.Path.UserDataXml))
            {
                return LoadFromFile();
            }

            return new UserData();
        }
    }
}
